package org.linlinjava.litemall.wx.service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.collections.CollectionUtils;
import org.linlinjava.litemall.db.domain.LitemallUserToken;
import org.linlinjava.litemall.wx.util.JwtHelper;

/**
 * 简单缓存的数据
 */
public class TokenCacheManager {
	private static ConcurrentHashMap<Integer, LitemallUserToken> cacheDataList = new ConcurrentHashMap<>();

	/**
	 * 缓存Token数据
	 *
	 * @param data
	 */
	public static void loadData(Integer cacheKey, LitemallUserToken cacheData) {
		cacheDataList.put(cacheKey, cacheData);
	}

	public static void loadAllData(List<LitemallUserToken> tokenList) {
		if (CollectionUtils.isNotEmpty(tokenList)) {
			for (LitemallUserToken token : tokenList) {
				if (token.getStatus() && isEnabled(token.getToken())) {
					loadData(token.getUserId(), token);
				}
			}
		}
	}

	public static LitemallUserToken getCacheData(Integer cacheKey) {
		return cacheDataList.get(cacheKey);
	}

	public static boolean isEnabled(String token) {
		JwtHelper jwtHelper = new JwtHelper();
		Integer userId = jwtHelper.verifyTokenAndGetUserId(token);
		if (userId == null || userId == 0) {
			return false;
		}
		return true;
	}

	/**
	 * 判断Token 是否过期
	 *
	 * @return
	 */
	public static boolean tokenExpire(Integer cacheKey) {
		LitemallUserToken cacheData = cacheDataList.get(cacheKey);
		if (cacheData == null) {
			return false;
		} else {
			if (!cacheData.getStatus()) {
				return false;
			}
			LocalDateTime expire = cacheData.getExpireDate();
			if (expire.isBefore(LocalDateTime.now())) {
				return false;
			} else {
				return true;
			}
		}
	}

	/**
	 * 清除所有缓存
	 */
	public static void clearAll() {
		cacheDataList = new ConcurrentHashMap<>();
	}
	/**
	 * 清除缓存数据
	 */
	public static void clears(List<Integer> userIdList) {
		if(CollectionUtils.isNotEmpty(userIdList)) {
			for(Integer userId : userIdList) {
				clear(userId);
			}
		}
	}

	/**
	 * 清除缓存数据
	 */
	public static void clear(Integer cacheKey) {
		LitemallUserToken cacheData = cacheDataList.get(cacheKey);
		if (cacheData != null) {
			cacheDataList.remove(cacheKey);
		}
	}
}
